package com.neusoft.restaurant.controller;

import com.alibaba.fastjson.JSON;
import com.neusoft.restaurant.config.utils.R;
import com.neusoft.restaurant.config.utils.SecurityUtils;
import com.neusoft.restaurant.entity.LoginUserVo;
import com.neusoft.restaurant.entity.SysUser;
import com.neusoft.restaurant.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhongda
 * @createTime: 2023/11/24 15:43
 * @email: fromzhongda@163.com
 * @description:
 */
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R login(@RequestBody SysUser userVo) {
//        userVo.setPassword(SecurityUtils.encryptPassword(userVo.getPassword()));
        System.out.println("前端传过来的登录数据："+userVo.toString());

        SysUser user = userService.selectUserByUserName(userVo.getUserName());
//        System.out.println(user);
        if (user == null) {
            userService.insertUser(userVo);

            user = userService.selectUserByUserName(userVo.getUserName());
//            return R.error(404, "用户不存在");
//            throw new BizException(404,"用户不存在");
        }else {
            boolean ok = SecurityUtils.matchesPassword(userVo.getPassword(), user.getPassword());
            if (!ok) {
                return R.error(404, "账号密码错误");
            }
        }

        String token = UUID.randomUUID().toString().replace("-", "");

//        System.out.println("token----->"+token);
        String jsonStr = JSON.toJSONString(user);
        redisTemplate.opsForValue().set("user:"+token, jsonStr, 1, TimeUnit.HOURS);//设置1小时过期 "user:"表示在Redis中创建一个文件夹
        return R.success().put("token", token);
    }


   //通过token获取用户信息
    @GetMapping
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String user = (String) redisTemplate.opsForValue().get("user:"+token);
        if (user==null){
            return R.error(400,"redis中不存在");
        }
        SysUser sysUser = JSON.parseObject(user, SysUser.class);
        return R.success(sysUser);
    }

    @GetMapping("/get")
    public R testInterceptor() {
        Long userId = this.getUserId();
        System.out.println("userId:"+userId);
        SysUser curUser = this.getCurUser();
        System.out.println("curUser:" + curUser);
        return R.success(curUser);
    }
}
